package com.bac.rentmap.ad.crawler.phone;

import java.util.ArrayList;
import java.util.List;

/**
 * Transform phone to uniform form.
 *
 * @author Andrew Osipenko
 */
public class PhoneNormalizer {
    private List<String> prefixes = new ArrayList<String>();

    public PhoneNormalizer() {
        prefixes = new ArrayList<String>();
        prefixes.add("029");
        prefixes.add("025");
        prefixes.add("044");
    }

    public String normalizePhone(String phone) {
        String res = phone.replaceAll("[\\+\\s\\(\\)\\/-]", "");
        if(res.startsWith("375")){
            res = res.replaceFirst("375", "0");
        }
        if (res.length() > 7) {
            for (String prefix : prefixes) {
                if (res.startsWith(prefix)) {
                    res = "8" + res;
                    break;
                }
            }
        }
        if (res.length() != 11) {
            throw new IllegalArgumentException("Can't normalize phone " + phone);
        }
        return res;
    }
}
